<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\admin\model\Comment;
use app\common\model\Category as CategoryModel;
/**
 * 投稿接口
 */
class Contribution extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $LitestoreGoods = null;
    protected $Manuscript = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 1;
        $this->LitestoreGoods = new \app\admin\model\LitestoreGoods;
        $this->Manuscript = new \app\admin\model\Manuscript;
    }  
     /**
     * 留言(留意后返回最新数据)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Contribution/comment)
     * @ApiParams   (name="content",type=string,required=true,description="留言内容")
     * @ApiParams   (name="contribution_id",type=id,required=true,description="稿件id")
     * @ApiParams   (name="status",type=int,required=false,description="不传就查最新数据，传1就查置顶的数据")
     * @ApiReturn   ({
   
        })
    
     */
    public function comment(){
        $params = input();
        $params['user_id'] = $this->user_id;
        $Comment = new Comment($params);
        $Comment->allowField(true)->save();
        $comment = $Comment->with('user')->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->where('contribution_id',$params['contribution_id'])->order('createtime desc')->select();
        Db::name('manuscript')->where('id',$params['contribution_id'])->setInc('comment_num');
        $this->success('评论成功',$comment);
    }

    /**
     * 发布稿件和修改稿件
     * @ApiSummary  (修改时传id过来.有二级分类就传二级分类名称过来)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Contribution/post)
     * @ApiParams   (name="id",type=int,required=true,description="修改时候传id过来")
     * @ApiParams   (name="type",type=string,required=true,description="传分区过来")
     * @ApiParams   (name="images",type=string,required=false,description="多个图片的情况下用逗号隔开")
     * @ApiParams   (name="category",type=string,required=true,description="第二级分类名称")
     * @ApiParams   (name="status",type=string,required=true,description="第一级分类:science=科普,evaluation=测评,question=问答,up_news=线上咨询,low_news=线下咨询")
     * @ApiParams   (name="title",type=string,required=false,description="标题")
     * @ApiParams   (name="content",type=string,required=false,description="描述详情")
     * @ApiReturn   ({
        
        })
     */
      public function post(){
        $params = input();
        $params['user_id'] = $this->user_id;

        if($params['id']){
            $res = $this->Manuscript->isUpdate(true)->save($params);
        }else{
            unset($params['id']);
            $res = $this->Manuscript->save($params);
        }

        if($res){
            $this->success('操作成功');
        }
      }


    /**
    * 获取投稿列表 switch等于1代表推荐,my_follow等于1代表是已关注的动态
    * @param int $type 传分区过来
    **/
      public function index(){
        $type = input('type');
        $my_follow = Db::name('user')->where('id',$this->user_id)->value('follow');
        $return = Db::name('manuscript as m')->join('user u','m.user_id = u.id')->field("m.*,FROM_UNIXTIME(m.createtime,'%Y-%m-%d %H:%i:%s') as createtime,u.avatar")->where(['m.type'=>$type])->order('m.createtime desc')->select();
        foreach ($return as $key => $value) {
            if($my_follow){
                $my_follow_array = explode(',', trim($my_follow,','));
                if(in_array($value['user_id'], $my_follow_array)){
                    $return[$key]['my_follow'] = 1;
                }else{
                    $return[$key]['my_follow'] = 0;
                }
            }else{
                $return[$key]['my_follow'] = 0;
            }
          $collect_array = json_decode($value['collect_array'],true);
          if(!empty($collect_array)){
            if(in_array($this->user_id,$collect_array )){
              $return[$key]['is_collect'] = 1;
            }else{
              $return[$key]['is_collect'] = 0;
            }
          }else{
            $return[$key]['is_collect'] = 0;
          }
          $dianzan_array = json_decode($value['dianzan_array'],true);
          if(!empty($dianzan_array)){
            if(in_array($this->user_id,$dianzan_array )){
              $return[$key]['is_dianzan'] = 1;
            }else{
              $return[$key]['is_dianzan'] = 0;
            }
          }else{
            $return[$key]['is_dianzan'] = 0;
          }
        }

        $this->success('获取投稿列表',$return);

      }

     /**
    * 搜索稿件 
    * @param string $type 传分区过来
    * @param string $title 搜索名称
    **/
      public function search(){
        $type = input('type');
        $title = input('title');
        $my_follow = Db::name('user')->where('id',$this->user_id)->value('follow');
        $return = Db::name('manuscript as m')->join('user u','m.user_id = u.id')->field("m.*,FROM_UNIXTIME(m.createtime,'%Y-%m-%d %H:%i:%s') as createtime,u.avatar")->where(['m.type'=>$type,'title'=>['like',"%$title%"]])->order('m.createtime desc')->select();
        foreach ($return as $key => $value) {
            if($my_follow){
                $my_follow_array = explode(',', trim($my_follow,','));
                if(in_array($value['user_id'], $my_follow_array)){
                    $return[$key]['my_follow'] = 1;
                }else{
                    $return[$key]['my_follow'] = 0;
                }
            }else{
                $return[$key]['my_follow'] = 0;
            }
          $collect_array = json_decode($value['collect_array'],true);
          if(!empty($collect_array)){
            if(in_array($this->user_id,$collect_array )){
              $return[$key]['is_collect'] = 1;
            }else{
              $return[$key]['is_collect'] = 0;
            }
          }else{
            $return[$key]['is_collect'] = 0;
          }
          $dianzan_array = json_decode($value['dianzan_array'],true);
          if(!empty($dianzan_array)){
            if(in_array($this->user_id,$dianzan_array )){
              $return[$key]['is_dianzan'] = 1;
            }else{
              $return[$key]['is_dianzan'] = 0;
            }
          }else{
            $return[$key]['is_dianzan'] = 0;
          }
        }
        $this->success('搜索稿件',$return);
      }


    /**
    * 获取投稿详情
    * @param int $contribution_id 稿件id
    **/
      public function detail(){
        $return['contribution'] = Db::name('manuscript as m')->join('user u','m.user_id = u.id')->field("m.*,FROM_UNIXTIME(m.createtime,'%Y-%m-%d %H:%i:%s') as createtime,u.avatar")->where('m.id',input('contribution_id'))->find();
        $collect_array = json_decode($return['contribution']['collect_array'],true);
        if(!empty($collect_array)){
            if(in_array($this->user_id,$collect_array )){
              $return['contribution']['is_collect'] = 1;
            }else{
              $return['contribution']['is_collect'] = 0;
            }
            }else{
            $return['contribution']['is_collect'] = 0;
            }
            $dianzan_array = json_decode($return['contribution']['dianzan_array'],true);
            if(!empty($dianzan_array)){
            if(in_array($this->user_id,$dianzan_array )){
              $return['contribution']['is_dianzan'] = 1;
            }else{
              $return['contribution']['is_dianzan'] = 0;
            }
            }else{
            $return['contribution']['is_dianzan'] = 0;
        }

        $Comment = new Comment();
        $return['comment'] = $Comment->with('user')->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->where('contribution_id',input('contribution_id'))->order('createtime desc')->select();

        $history = Db::name('user')->where(['id'=>$this->user_id])->value('history');
        $start_pos = strpos($history, input('contribution_id'));
        if(empty($start_pos)){
            //排在第一位
            $new_history = ','.input('contribution_id').$history;
            
        }else{
            // 将旧的id拿到第一位
            $id_length = strlen(input('contribution_id'));
            $jiequ_str = substr($history, 0,$start_pos-1);
            $jiequ_end = substr($history, $start_pos+1);
            
            $new_history = ','.input('contribution_id').$jiequ_str.$jiequ_end;
        }

        Db::name('user')->where(['id'=>$this->user_id])->update(['history'=>$new_history]);

        $this->success('获取投稿详情',$return);

      }
     /**
     * 点赞和取消点赞
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/contribution/dianzan)
     * @ApiParams   (name="contribution_id",type=int,required=false,description="id")
     * @ApiParams   (name="status",type=int,required=false,description="1是点赞，0是取消点赞")
     * @ApiReturn   ({
        })
     */
    public function dianzan(){
      $contribution_id = input('contribution_id');
      $status = input('status');
      $dianzan_array = Db::name('manuscript')->where(['id'=>$contribution_id])->value('dianzan_array');
      $dianzan_array = json_decode($dianzan_array,true);
      if($status){
        if(!empty($dianzan_array)){

          if(in_array($this->user_id, $dianzan_array)){
            $this->error('请勿重复点赞');die;
          }
          // $dianzan_array = array_push($dianzan_array, $this->user_id);
          $dianzan_array[] = $this->user_id;

          $dianzan_array = json_encode($dianzan_array);

          Db::name('manuscript')->where(['id'=>$contribution_id])->setInc('dianzan_num');
          $res = Db::name('manuscript')->where(['id'=>$contribution_id])->update(['dianzan_array'=>$dianzan_array]);
          if($res){
            $my_dianzan = Db::name('dianzan')->where(['user_id'=>$this->user_id])->value('dianzan');
            $my_dianzan = json_decode($my_dianzan,true);
            $my_dianzan[] = $contribution_id;
            $my_dianzan = json_encode($my_dianzan);
            Db::name('dianzan')->where(['user_id'=>$this->user_id])->update(['dianzan'=>$my_dianzan]);
            $this->success('点赞成功');
          }

        }else{

          $dianzan_array = [0=>$this->user_id];
          $dianzan_array = json_encode($dianzan_array);

          Db::name('manuscript')->where(['id'=>$contribution_id])->setInc('dianzan_num');
          $res = Db::name('manuscript')->where(['id'=>$contribution_id])->update(['dianzan_array'=>$dianzan_array]);
          if($res){
            $my_dianzan = Db::name('dianzan')->where(['user_id'=>$this->user_id])->value('dianzan');
            $my_dianzan = json_decode($my_dianzan,true);
            $my_dianzan[] = $contribution_id;
            $my_dianzan = json_encode($my_dianzan);
            Db::name('dianzan')->where(['user_id'=>$this->user_id])->update(['dianzan'=>$my_dianzan]);
            $this->success('点赞成功');
          }

        }

      //取消点赞
      } else{

        $key = array_search($this->user_id, $dianzan_array);

        if ($key !== false){

          unset($dianzan_array[$key]);
          $dianzan_array = json_encode($dianzan_array);
          Db::name('manuscript')->where(['id'=>$contribution_id])->setDec('dianzan_num');
          $res = Db::name('manuscript')->where(['id'=>$contribution_id])->update(['dianzan_array'=>$dianzan_array]);
          if($res){
            $my_dianzan = Db::name('dianzan')->where(['user_id'=>$this->user_id])->value('dianzan');

            $my_dianzan = json_decode($my_dianzan,true);
            $dianzan_key = array_search($contribution_id, $my_dianzan);
            unset($my_dianzan[$dianzan_key]);
            $my_dianzan = json_encode($my_dianzan);
            Db::name('dianzan')->where(['user_id'=>$this->user_id])->update(['dianzan'=>$my_dianzan]);
            $this->success('取消点赞成功');
          } 
        }else{
          $this->error('操作失败');
        }
      } 
  }

      /**
     * 收藏和取消收藏
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/contribution/collect)
     * @ApiParams   (name="contribution_id",type=int,required=false,description="id")
     * @ApiParams   (name="status",type=int,required=false,description="1是收藏，0是取消收藏")
     * @ApiReturn   ({
        })
     */
    public function collect(){
      $contribution_id = input('contribution_id');
      $status = input('status');
      $collect_array = Db::name('manuscript')->where(['id'=>$contribution_id])->value('collect_array');
      $collect_array = json_decode($collect_array,true);
      if($status){
        if(!empty($collect_array)){

          if(in_array($this->user_id, $collect_array)){
            $this->error('请勿重复收藏');die;
          }
          // $collect_array = array_push($collect_array, $this->user_id);
          $collect_array[] = $this->user_id;

          $collect_array = json_encode($collect_array);

          Db::name('manuscript')->where(['id'=>$contribution_id])->setInc('collect_num');
          $res = Db::name('manuscript')->where(['id'=>$contribution_id])->update(['collect_array'=>$collect_array]);
          if($res){
            $my_collect = Db::name('collect')->where(['user_id'=>$this->user_id])->value('collect');
            $my_collect = json_decode($my_collect,true);
            $my_collect[] = $contribution_id;
            $my_collect = json_encode($my_collect);
            Db::name('collect')->where(['user_id'=>$this->user_id])->update(['collect'=>$my_collect]);
            $this->success('收藏成功');
          }

        }else{

          $collect_array = [0=>$this->user_id];
          $collect_array = json_encode($collect_array);

          Db::name('manuscript')->where(['id'=>$contribution_id])->setInc('collect_num');
          $res = Db::name('manuscript')->where(['id'=>$contribution_id])->update(['collect_array'=>$collect_array]);
          if($res){
            $my_collect = Db::name('collect')->where(['user_id'=>$this->user_id])->value('collect');
            $my_collect = json_decode($my_collect,true);
            $my_collect[] = $contribution_id;
            $my_collect = json_encode($my_collect);
            Db::name('collect')->where(['user_id'=>$this->user_id])->update(['collect'=>$my_collect]);
            $this->success('收藏成功');
          }

        }

      //取消收藏
      } else{

        $key = array_search($this->user_id, $collect_array);

        if ($key !== false){

          unset($collect_array[$key]);
          $collect_array = json_encode($collect_array);
          Db::name('manuscript')->where(['id'=>$contribution_id])->setDec('collect_num');
          $res = Db::name('manuscript')->where(['id'=>$contribution_id])->update(['collect_array'=>$collect_array]);
          if($res){
            $my_collect = Db::name('collect')->where(['user_id'=>$this->user_id])->value('collect');

            $my_collect = json_decode($my_collect,true);
            $collect_key = array_search($contribution_id, $my_collect);
            unset($my_collect[$collect_key]);
            $my_collect = json_encode($my_collect);
            Db::name('collect')->where(['user_id'=>$this->user_id])->update(['collect'=>$my_collect]);
            $this->success('取消收藏成功');
          } 
        }else{
          $this->error('操作失败');
        }
       } 
    }









    

  

}
